import { setCookie, removeCookie } from '@/utils/cookie';
import { DEMO_AUTH_TOKEN_FRONT } from '@/common/constant';
import router from '@/router';

const state = {
  userInfo: {}, // 用户数据
  roles: [], // 角色状态
};

const mutations = {
  // 登录状态保存
  SET_LOGIN: (state, user) => {
    state.userInfo = user;
    setCookie(DEMO_AUTH_TOKEN_FRONT, user.token);
  },
  // 添加userInfo信息
  ADD_USERINFO: (state, addInfo) => {
    let keys = Object.keys(addInfo);
    for (let i = 0; i < keys.length; i++) {
      state.userInfo[keys[i]] = addInfo[keys[i]];
    }
  },
  // 角色状态保存
  SET_ROLE(state, roles) {
    state.roles = roles;
  },
  // 注销登录状态
  SET_LOGOUT(state) {
    state.userInfo = {};
    state.roles = [];
    sessionStorage.removeItem('online');
    removeCookie(DEMO_AUTH_TOKEN_FRONT);
  },
};

const actions = {
  logout({ commit }) {
    commit('SET_LOGOUT');
    router.push('/login');
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
